"""
Flask应用工厂函数
"""
import os
from flask import Flask
from app.config import config
from app.extensions import init_extensions
from app.api import blueprints
from flask_cors import CORS

def create_app(config_name=None):
    """创建Flask应用实例"""
    if config_name is None:
        config_name = os.environ.get('FLASK_ENV', 'default')
    
    app = Flask(__name__, static_folder='static', static_url_path='')
    CORS(app)
    # 加载配置
    app.config.from_object(config[config_name])
    
    # 初始化扩展
    init_extensions(app)

    # 注册蓝图
    for blueprint in blueprints:
        app.register_blueprint(blueprint)
    
    # 添加静态文件服务 - 服务前端打包文件
    @app.route('/')
    def index():
        return app.send_static_file('index.html')
    
    @app.route('/<path:path>')
    def static_files(path):
        # 如果请求的文件不存在，返回index.html以支持前端路由
        if os.path.exists(os.path.join(app.static_folder, path)):
            return app.send_static_file(path)
        else:
            return app.send_static_file('index.html')
    
    return app